package com.ruoyi.app.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.app.annotation.AppSecurity;
import com.ruoyi.app.util.ReqMsg;
import com.ruoyi.app.util.RspMsg;
import com.ruoyi.bizsys.domain.AppUserMark;
import com.ruoyi.bizsys.service.IAppUserMarkService;
import com.ruoyi.business.common.AsyncService;
import com.ruoyi.common.enums.UserTagEnum;
import com.ruoyi.bizsys.utils.BizConstants;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.Func;
import com.ruoyi.extdata.common.config.VerifyCodeConfig;
import com.ruoyi.sms.domain.SmsSendData;
import com.ruoyi.sms.domain.SmsSendReq;
import com.ruoyi.sms.service.ISmsService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 短信接口
 *
 * @Author: Jamnsin
 * @Date: 2021/01/14 6:06 下午
 */
@Slf4j
@Api("短信发送及校验接口")
@RestController
@RequestMapping("/sms")
public class SmsController extends BaseController {

    @Autowired
    ISmsService smsService;

    @Autowired
    VerifyCodeConfig verifyCodeConfig;

    @Autowired
    AsyncService asyncService;

    @Autowired
    private IAppUserMarkService appUserMarkService;

    /**
     * 发送短信验证码  基于运营商优先级规则发送短信验证码
     */
    @AppSecurity
    @ApiOperation("发送短信验证码")
    @PostMapping("/code")
    @Log(title = "验证码", businessType = BusinessType.SMS)
    public RspMsg sendCode(@Validated @RequestBody ReqMsg reqMsg) {
        SmsSendReq smsReq = JSON.parseObject(reqMsg.getData().toString(), SmsSendReq.class);
        log.info("请求data：{}", JSON.toJSONString(smsReq));
        checkAttribute(smsReq);
        SmsSendData smsData = smsService.sendVerifyCode(smsReq, true);
        // 返回 uuid                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 .
        JSONObject smsCode = new JSONObject();
        smsCode.put("uuid", smsData.getUuid());
        if ("0".equals(smsReq.getIsServerSend())) {
            smsCode.put("verifyCode", smsData.getVerifyCode());
            smsCode.put("content", smsData.getContent());
        }
        //注册标签
        if (BizConstants.SMS_TYPE_REGISTER.equals(smsReq.getSmsType())) {
            QueryWrapper<AppUserMark> wrapper = new QueryWrapper<AppUserMark>().eq("register_phone", smsData.getPhoneNumber());
            wrapper.last("limit 1");
            AppUserMark userMark = appUserMarkService.getOne(wrapper);
            //用户标签为空
            if (Func.isEmpty(userMark)) {
                //AppUserMark appUserMark = AppUserMark.builder().userId(smsData.getPhoneNumber()).registerPhone(smsData.getPhoneNumber()).build();
                asyncService.apdUserTag(AppUserMark.builder().userId(smsData.getPhoneNumber()).registerPhone(smsData.getPhoneNumber()).build(), UserTagEnum.UN_REGISTERED);
            }
        }
        return RspMsg.RspMsgOk(smsCode);
    }

    /**
     * 发送whatsApp验证码
     */
    @AppSecurity
    @ApiOperation("发送whatsApp验证码")
    @PostMapping("/whatsApp")
    @Log(title = "whatsApp验证码", businessType = BusinessType.WHATSAPP)
    public RspMsg sendWhatsApp(@Validated @RequestBody ReqMsg reqMsg) {
        SmsSendReq smsReq = JSON.parseObject(reqMsg.getData().toString(), SmsSendReq.class);
        log.info("请求data：{}", JSON.toJSONString(smsReq));

        checkAttribute(smsReq);
        SmsSendData smsData = smsService.sendWhatsAppVerifyCode(smsReq);

        // 返回 uuid                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 .
        JSONObject smsCode = new JSONObject();
        smsCode.put("uuid", smsData.getUuid());
//        if ("0".equals(smsReq.getIsServerSend())) {
//            smsCode.put("verifyCode", smsData.getVerifyCode());
//            smsCode.put("content", smsData.getContent());
//        }
        return RspMsg.RspMsgOk(smsCode);
    }

    /**
     * 发送枫软 语音验证码
     */
    @AppSecurity
    @ApiOperation("发送枫软 语音验证码")
    @PostMapping("/voiceOtp")
    @Log(title = "发送枫软 语音验证码", businessType = BusinessType.VOICEOTP)
    public RspMsg sendVoiceOtp(@Validated @RequestBody ReqMsg reqMsg) {
        SmsSendReq smsReq = JSON.parseObject(reqMsg.getData().toString(), SmsSendReq.class);
        log.info("请求data：{}", JSON.toJSONString(smsReq));

        checkAttribute(smsReq);
        SmsSendData smsData = smsService.sendFengRuanVoiceOtp(smsReq);
        // 返回 uuid                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 .
        JSONObject smsCode = new JSONObject();
        smsCode.put("uuid", smsData.getUuid());
        if ("0".equals(smsReq.getIsServerSend())) {
            smsCode.put("verifyCode", smsData.getVerifyCode());
            smsCode.put("content", smsData.getContent());
        }
        return RspMsg.RspMsgOk(smsCode);
    }

    /**
     * whats App 验证码校验
     */
    @AppSecurity
    @ApiOperation("whatsApp验证码")
    @PostMapping("/verifyWhatsApp")
    @Log(title = "whatsApp验证码", businessType = BusinessType.WHATSAPP)
    public RspMsg verifyWhatsApp(@Validated @RequestBody ReqMsg reqMsg) {
        JSONObject object = JSON.parseObject(reqMsg.getData().toString());
        log.info("请求data：{}", JSON.toJSONString(object));
        JSONObject jsonObject = new JSONObject();
        SmsSendData smsSendData = SmsSendData.builder()
                .phoneNumber(object.getString("phoneNumber")).verifyCode(object.getString("verifyCode")).build();
        boolean isValid = smsService.verifyWhatsAppCode(smsSendData);
        jsonObject.put("valid", isValid);
        jsonObject.put("status", 200);
        return RspMsg.RspMsgOk(jsonObject);
    }

}
